package cn.xiaobai.configuration;

import cn.xiaobai.annotaion.EventSubscriber;
import cn.xiaobai.listener.RedisClientListener;
import cn.xiaobai.subscriber.RedisEventBusSubscriber;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author yangdaji
 * @Date 2023/11/2
 * @PackageName cn.xiaobai.configuration
 * @ClassName SubscriberService
 */
@Component
public class SubscriberService implements ApplicationContextAware {

    @Autowired
    private RedisClientListener redisClientListener;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Environment environment = applicationContext.getEnvironment();
        subscriber(applicationContext, environment);
    }


    private void subscriber(ApplicationContext applicationContext, Environment environment) {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(EventSubscriber.class);
        beansWithAnnotation.values().forEach(sub -> {
            EventSubscriber annotation = AnnotationUtils.findAnnotation(sub.getClass(), EventSubscriber.class);
            String[] topics = annotation.topics();
            if (topics.length > 0) {
                for (String topic : topics) {
                    String top = environment.resolvePlaceholders(topic);
                    RedisEventBusSubscriber redisEventBusSubscriber = new RedisEventBusSubscriber(sub);
                    redisEventBusSubscriber.bindProxy();
                    redisClientListener.subscriber(top, redisEventBusSubscriber);
                }
            }
        });
    }


}
